#!/bin/bash

echo "Executing script by: caozhenho 24055060153"
echo "-----------------------------------------"

SOURCE_FILE="scores.txt"
OUTPUT_DIR="students"

# Step 1: Check if the source file exists
if [ ! -f "$SOURCE_FILE" ]; then
    echo "Error: Source file '$SOURCE_FILE' not found!"
    exit 1
fi

# Step 2: Create the output directory
mkdir -p "$OUTPUT_DIR"

# Step 3: Use while read loop to read file content
while read name gender id java_subj java_score python_subj python_score cpp_subj cpp_score linux_subj linux_score; do
    
    # Step 4: Calculate total score
    total=$(( java_score + python_score + cpp_score + linux_score ))
    
    # Calculate average score (keep one decimal place)
    average=$(echo "scale=1; $total / 4" | bc)
    
    # Define output file path
    output_file="$OUTPUT_DIR/$name.txt"
    
    # Write student information to file
    echo "name: $name" > "$output_file"
    echo "id: $id" >> "$output_file"
    echo "gender: $gender" >> "$output_file"
    echo "scores: $java_subj $java_score $python_subj $python_score $cpp_subj $cpp_score $linux_subj $linux_score" >> "$output_file"
    echo "total: $total" >> "$output_file"
    echo "average: $average" >> "$output_file"
    
    echo "Created file: $output_file"

# Redirect input from the source file at the end of the while loop
done < "$SOURCE_FILE"

echo "-----------------------------------------"
echo "All student files have been created in the '$OUTPUT_DIR' directory."
exit 0